package com.order.controller.sys.common;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.ext.plugin.shiro.ClearShiro;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StringKit;
import com.order.controller.BaseController;
import com.order.model.sys.SysUser;

@ControllerBind(controllerKey= "/common")
public class LoginController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	
	/**系统登录页面*/
	@ClearShiro
	public void index(){
		setAttr("root",getRequest().getContextPath());
		render("/common/login.htm");
	}
	

	/**用户登录方法*/
	public void loginSubmit(){
		String userName = null;
		String password = null;
		try {
			userName = URLDecoder.decode(getPara("username", "").trim(), "UTF-8");
			password = getPara("password", "").trim();
		} catch (UnsupportedEncodingException e) {
			log.error("用户名在转URLDecoder过程中出错!");
		}
		log.info("用户认证开始:" + userName + " , " + password); 
		AuthenticationToken token = new UsernamePasswordToken(userName, password); 
		Subject currentUser = SecurityUtils.getSubject();//当前的用户
		
		//验证系统是否被禁用或存在（可用）
		if(!SysUser.isUserEnabled(userName)){
			setAttr("msg", "unabled");
			renderJson();
			return;
		}
		//令牌验证
		if ((StringKit.notBlank(userName) && StringKit.notBlank(password))) {
			try {
				currentUser.login(token);
				log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
				log.info("用户认证完毕:" + userName);
				log.info("用户认证地址:" + getRequest().getRemoteAddr());
			} catch (UnknownAccountException uae) {
				log.info("用户认证失败:" + "username wasn't in the system.");
			} catch (IncorrectCredentialsException ice) {
				log.info("用户认证失败:" + "password didn't match.");
			} catch (LockedAccountException lae) {
				log.info("用户认证失败:"+ "account for that username is locked - can't login.");
			} catch (AuthenticationException ae) {
				log.info("用户认证失败:" + "unexpected condition.");
			}
		}
		
		//验证是否通过 
		if(currentUser.isAuthenticated()){
			setAttr("msg", "success");	
		}else{
			setAttr("msg", "fail");
		}
		renderJson();
	}
}
